package com.lab.book.server.message;

import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.lab.book.common.bean.LoginDetail;
import com.lab.book.common.bean.LoginHistory;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.topic.loginHistory}", consumerGroup = "book-server-consumer-group")
public class LoginHistoryReceiver implements RocketMQListener<LoginHistory> {
	@Autowired
	private MongoTemplate mongoTemplate;

	// RocketMQ 接收消息
	@Override
	public void onMessage(LoginHistory loginHistory) {
		log.info(StringUtils.center("receiverLoginHistory", 52, "="));

		LoginDetail detail = loginHistory.getDetails().iterator().next();

		Query query = Query.query(Criteria.where("username").is(loginHistory.getUsername()));

		Update update = Update.update("lastLoginDate", loginHistory.getLastLoginDate());
		update = update.addToSet("details", detail);
		update = update.inc("in1HourFailureTimes", loginHistory.getIn1HourFailureTimes());

		mongoTemplate.upsert(query, update, LoginHistory.class);
	}
}
